package org.atlantis.mongo.datatype;

import java.util.Date;

import org.atlantis.mongo.MongoFactory;
import org.atlantis.mongo.TrialUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBCollection;

public class DataIndexTypeTrial {

	// 使用int类型。插入60万条记录，数据占用18.311MB，索引占用33.484MB。
	public void intTypes() {
		DBCollection coll = MongoFactory.getDB().getCollection("trial.inttypes");
		coll.ensureIndex(new BasicDBObject("name", -1));
		for (int i = 0; i < 600000; i++) {
			coll.insert(new BasicDBObject("name", i));
		}
		CommandResult cr = coll.getStats();
		printSize(cr);
	}

	// 使用long类型。插入60万条记录，数据占用20.599MB，索引占用38.109MB。
	public void longTypes() {
		DBCollection coll = MongoFactory.getDB().getCollection("trial.longtypes");
		coll.ensureIndex(new BasicDBObject("name", -1));
		for (int i = 0; i < 600000; i++) {
			coll.insert(new BasicDBObject("name", (long) i));
		}
		CommandResult cr = coll.getStats();
		printSize(cr);
	}

	// 使用String类型。插入60万条记录，数据占用22.884MB，索引占用40.102MB。
	public void stringTypes() {
		DBCollection coll = MongoFactory.getDB().getCollection("trial.stringtypes");
		coll.ensureIndex(new BasicDBObject("name", -1));
		for (int i = 0; i < 600000; i++) {
			coll.insert(new BasicDBObject("name", "" + i));
		}
		CommandResult cr = coll.getStats();
		printSize(cr);
	}

	// 使用Date类型。插入60万条记录，数据占用20.599MB，索引占用38.109MB。
	public void dateTypes() {
		long now = System.currentTimeMillis();
		DBCollection coll = MongoFactory.getDB().getCollection("trial.datetypes");
		coll.ensureIndex(new BasicDBObject("name", -1));
		for (int i = 0; i < 600000; i++) {
			coll.insert(new BasicDBObject("name", new Date(now + i)));
		}
		CommandResult cr = coll.getStats();
		printSize(cr);
	}
	
	private void printSize(CommandResult cr) {
		String dataSize = TrialUtils.formatSize(cr.getLong("size"));
		String nameIndexSize = TrialUtils.formatSize(((BasicDBObject) cr.get("indexSizes")).getLong("name_-1"));
		System.out.println("dataSize: " + dataSize);
		System.out.println("nameIndexSize: " + nameIndexSize);
	}

	public static void main(String[] args) {
		DataIndexTypeTrial trial = new DataIndexTypeTrial();
		trial.dateTypes();
	}
}
